import { login, logout, getInfo } from 'api/user';
import Cookies from 'js-cookie';
import Storage from '@/utils/storage'

const userStorage = new Storage('user')

const user = {
  state: {
    uid: Cookies.get('uid'),
    username: userStorage.get('user').username,
    avatar: userStorage.get('user').avatar,
    type: userStorage.get('user').type,
    isteacher: userStorage.get('user').isteacher,
    org: userStorage.get('user').org,
    phone_no: userStorage.get('user').phone_no
  },

  mutations: {
    SET_UID: (state, uid) => {
      state.uid = uid;
    },
    SET_NAME: (state, username) => {
      state.username = username;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_TYPE: (state, type) => {
      state.type = type;
    },
    SET_TEACHER: (state, isteacher) => {
      state.isteacher = isteacher
    },
    SET_ORG: (state, org) => {
      state.org = org
    },
    SET_PHONE: (state, phone_no) => {
      state.phone_no = phone_no
    }
  },

  actions: {
    // 登录
    LogIn({ commit }, loginForm) {
      const phone = loginForm.phone.trim();
      return new Promise((resolve, reject) => {
        login(phone, loginForm.password).then(res => {
          Cookies.set('uid', res.user.uid);
          userStorage.set(res.user);
          commit('SET_UID', res.user.uid);
          commit('SET_NAME', res.user.username);
          commit('SET_AVATAR', res.user.avatar);
          commit('SET_TYPE', res.user.type);
          commit('SET_TEACHER', res.user.teacher);
          commit('SET_ORG', res.user.org);
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_UID', '');
          Cookies.remove('uid');
          userStorage.clear();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          Cookies.set('uid', res.info.uid);
          userStorage.set(res.info);
          commit('SET_UID', res.info.uid);
          commit('SET_NAME', res.info.username);
          commit('SET_AVATAR', res.info.avatar);
          commit('SET_TYPE', res.info.type);
          commit('SET_TEACHER', res.info.isteacher);
          commit('SET_ORG', res.info.org);
          commit('SET_PHONE', res.info.phone_no);
          resolve(res)
        }).catch(error => {
          reject(error);
        });
      });
    }
  }
};

export default user;
